<template>
  <div class="global-box">
    <a-form-model
      class="agreeForm"
      ref="agreeForm"
      :model="agreeForm"
      :rules="agreeFormRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-model-item label="商品名称"> {{ agreeForm.name }} </a-form-model-item>
      <a-form-model-item label="考试次数"> {{ agreeForm.number }} </a-form-model-item>
      <a-form-model-item label="商品有效期" prop="validity">
        <a-radio-group v-model="agreeForm.validity" @change="validityChange">
          <a-radio :value="item.value" v-for="item in validityList" :key="item.value">{{
            item.label
          }}</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="有效期时间" prop="expiredValue" v-if="agreeForm.validity === 0">
        <a-row :gutter="10">
          <a-col :span="3">
            <a-select v-model="agreeForm.expiredGoods" @change="expiredGoodsChange">
              <a-select-option :key="item.value" :value="item.value" v-for="item in expiredList">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="5">
            <a-input
              v-if="agreeForm.expiredGoods === 0"
              v-model="agreeForm.expiredValue"
              placeholder="请输入天数"
            ></a-input>
            <a-input
              v-if="agreeForm.expiredGoods === 1"
              v-model="agreeForm.expiredValue"
              placeholder="请输入月数"
            ></a-input>
            <a-select
              v-if="agreeForm.expiredGoods === 2"
              v-model="agreeForm.expiredValue"
              placeholder="请选择年份"
            >
              <a-select-option
                :key="item.value"
                :value="item.value"
                v-for="item in expiredYearList"
                >{{ item.label }}</a-select-option
              >
            </a-select>
            <a-date-picker
              v-if="agreeForm.expiredGoods === 3"
              v-model="agreeForm.expiredValue"
              show-time
              @change="expiredDate"
              placeholder="请选择固定时间"
            />
          </a-col>
        </a-row>
      </a-form-model-item>
      <a-form-model-item label="考季数" prop="examSeason" v-if="agreeForm.validity === 1">
        <a-input
          v-model="agreeForm.examSeason"
          placeholder="请输入考季数"
          style="width: 30%"
        ></a-input>
      </a-form-model-item>
      <a-form-model-item label="关联协议">
        <a @click="addAgreeVisible = true">选择协议</a>
        <a-table
          v-if="data && data.length > 0"
          :columns="columns"
          :data-source="data"
          :pagination="false"
          :rowKey="record => record.protocolId"
        >
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleLookAgree(record)">查看协议</a>
              <a-divider type="vertical" />
              <a @click="handleDelete(record)">删除</a>
            </template>
          </span>
        </a-table>
      </a-form-model-item>
      <a-form-model-item label="退费金额">{{
        (data.length !== 0 && data[0].refundAmount) || ''
      }}</a-form-model-item>
      <a-form-model-item label="重修次数">{{
        (data.length !== 0 && data[0].studyNum) || ''
      }}</a-form-model-item>
      <a-form-model-item label="售后有效期">{{
        (data.length !== 0 && data[0].validityTime) || ''
      }}</a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 14, offset: 5 }">
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </a-form-model-item>
    </a-form-model>
    <a-modal
      title="添加协议"
      :visible="addAgreeVisible"
      @ok="addAgreeHandleOk"
      @cancel="addAgreeHandleCancel"
      okText="提交"
      cancelText="取消"
      width="45%"
    >
      <div class="form-wrapper">
        <a-form layout="inline">
          <a-row :gutter="20">
            <a-col :md="8">
              <a-form-item label="课程目录" class="w80">
                <a-cascader
                  :field-names="{ label: 'value', value: 'id', children: 'children' }"
                  :options="directoryOptions"
                  :default-value="queryParam.directory"
                  :load-data="loadData"
                  placeholder="请选择课程目录"
                  change-on-select
                  v-model="queryParam.directory"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <a-form-item label="协议类型" class="w80">
                <a-select v-model="queryParam.type" placeholder="请选择协议类型">
                  <a-select-option :value="item.value" :key="item.value" v-for="item in agreeList">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <a-form-item label="协议ID" class="w80">
                <a-input v-model="queryParam.id" placeholder="请输入协议ID" />
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <a-form-item label="协议名称" class="w80">
                <a-input v-model="queryParam.name" placeholder="请输入协议名称" />
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <a-form-item label="所属事业部" class="w80">
                <a-select v-model="queryParam.affiliation" placeholder="请选择" default-value="0">
                  <a-select-option
                    :value="item.jiGouTableId"
                    :key="item.jiGouTableId"
                    v-for="item in affiliationList"
                  >
                    {{ item.jiGouName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="search">筛选</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
        :rowSelection="rowSelection"
        :columns="addAgreeColumns"
        :data-source="caddAgreeData"
        :pagination="addAgreePagination"
        :rowKey="record => record.protocolId"
      >
      </a-table>
    </a-modal>
  </div>
</template>
<script>
import { viewAgree, directory, affiliation, agreeList, goodsArgee } from '@/api/product/goods'
const columns = [
  {
    title: '协议ID',
    dataIndex: 'protocolId',
    align: 'center'
  },
  {
    title: '协议名称',
    dataIndex: 'protocolName',
    align: 'center'
  },
  {
    title: '所属模板ID',
    dataIndex: 'protocolTemplateId',
    align: 'center'
  },
  {
    title: '所属模板',
    dataIndex: 'protocolTemplateName',
    align: 'center'
  },
  {
    title: '协议类型',
    dataIndex: 'protocolCategory',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]
const addAgreeColumns = [
  {
    title: '协议ID',
    dataIndex: 'protocolId',
    align: 'center'
  },
  {
    title: '协议名称',
    dataIndex: 'protocolName',
    align: 'center'
  },
  {
    title: '协议类型',
    dataIndex: 'protocolCategory',
    align: 'center'
  },
  {
    title: '所属协议模板',
    dataIndex: 'protocolTemplateName',
    align: 'center'
  }
]
export default {
  data () {
    return {
      columns,
      data: [],
      addAgreeColumns,
      caddAgreeData: [],
      addAgreeVisible: false,
      addAgreePagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.addAgreePagination.defaultCurrent = 1
          this.addAgreePagination.defaultPageSize = pageSize
          this.getAgreeList()
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.addAgreePagination.defaultCurrent = current
          this.addAgreePagination.defaultPageSize = size
          this.getAgreeList()
        }
      },
      agreeForm: {
        name: '',
        number: '',
        validity: 0,
        expiredGoods: 0,
        expiredValue: undefined,
        examSeason: ''
      },
      expiredYearList: [{
        label: '一年',
        value: 1
      }, {
        label: '二年',
        value: 2
      }, {
        label: '三年',
        value: 3
      }, {
        label: '四年',
        value: 4
      }, {
        label: '五年',
        value: 5
      }, {
        label: '六年',
        value: 6
      }, {
        label: '七年',
        value: 7
      }, {
        label: '八年',
        value: 8
      }, {
        label: '九年',
        value: 9
      }, {
        label: '十年',
        value: 10
      }, {
        label: '终生',
        value: 0
      }],
      expiredList: [{
        label: '天',
        value: 0
      }, {
        label: '月',
        value: 1
      }, {
        label: '年',
        value: 2
      }, {
        label: '固定时间',
        value: 3
      }],
      loading: false,
      labelCol: { span: 3 },
      wrapperCol: { span: 15 },
      agreeFormRules: {
        validity: [
          { required: true, message: '请选择所属app', trigger: 'change' }
        ],
        examSeason: [
          { required: true, message: '请输入考季数', trigger: 'blur' }
        ],
        expiredValue: [
          { required: true, message: '请输入有效期时间', trigger: ['blur', 'change'] }
        ]
      },
      queryParam: {
        directory: [],
        type: undefined,
        id: '',
        name: '',
        affiliation: undefined
      },
      directoryOptions: [],
      affiliationList: [],
      agreeList: [
        {
          label: '通用',
          value: 1
        },
        {
          label: '退费',
          value: 2
        },
        {
          label: '重修',
          value: 3
        },
        {
          label: '退费和重修',
          value: 4
        }
      ],
      packageId: '',
      selectedRows: [],
      selectedRowKeys: [],
      validityList: [
        {
          label: '非季考',
          value: 0
        },
        {
          label: '季考',
          value: 1
        }
      ]
    }
  },
  computed: {
    rowSelection () {
      const that = this
      return {
        type: 'radio',
        selectedRowKeys: that.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          that.selectedRowKeys = selectedRowKeys
          that.selectedRows = selectedRows
        },
        getCheckboxProps: (record) => ({
          props: {
            checked: that.selectedRowKeys.indexOf(record.protocolId) > -1
          }
        })
      }
    }
  },
  mounted () {
    this.getDirectory()
    this.getAffiliation()
    if (this.$route.params.packageId && this.$route.params.packageId !== '') {
      this.packageId = this.$route.params.packageId
      this.getData()
      this.getAgreeList()
    }
  },
  methods: {
    // 获取数据
    getData () {
      const data = {
        packageId: this.packageId
      }
      viewAgree(data).then(res => {
        if (res.code === '1') {
          this.agreeForm.name = res.data.packageName
          this.agreeForm.number = res.data.examinationNum
          this.agreeForm.validity = res.data.termOfValidity
          if (res.data.agreementInfoDTO && res.data.agreementInfoDTO.length !== 0) {
            this.data = [{
              protocolId: res.data.agreementInfoDTO[0].protocolId,
              protocolName: res.data.agreementInfoDTO[0].protocolName,
              protocolTemplateId: res.data.agreementInfoDTO[0].templateId,
              protocolTemplateName: res.data.agreementInfoDTO[0].templateName,
              protocolCategory: res.data.agreementInfoDTO[0].protocolType
            }]
          }
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 获取协议列表数据
    getAgreeList () {
      const data = {
        currentPage: this.addAgreePagination.defaultCurrent,
        pageSize: this.addAgreePagination.defaultPageSize,
        deptId: this.queryParam.affiliation || 0,
        directoryId: this.queryParam.directory[0] || 0,
        enable: 2,
        examId: this.queryParam.directory[1] || 0,
        protocolCategory: this.queryParam.type || 0,
        protocolId: this.queryParam.id || 0,
        protocolName: this.queryParam.name || '',
        protocolTemplateId: 0
      }
      agreeList(data).then(res => {
        if (res.code === '1') {
          this.addAgreePagination.total = res.data.totalSize
          this.caddAgreeData = res.data.rows
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 提交
    onSubmit () {
      this.$refs.agreeForm.validate(valid => {
        if (valid) {
          const data = {
            agreementId: this.data[0].id,
            termOfValidity: this.agreeForm.validity,
            packageId: this.packageId
          }
          if (this.agreeForm.validity === 1) {
            data.examSeasonNum = this.agreeForm.examSeason
          } else {
            data.termOfValidityTimeType = this.agreeForm.expiredGoods
            if (this.agreeForm.expiredGoods === 3) {
              data.fixedTime = this.agreeForm.expiredValue
            } else {
              data.termOfValidityTimeNum = this.agreeForm.expiredValue
            }
          }
          goodsArgee(data).then(res => {
            if (res.code === '1') {
              this.$message.success(res.msg)
              this.$router.push({
                name: 'productGoods'
              })
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err.msg)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    expiredDate (date, dateString) {
      if (this.agreeForm.expiredGoods === 3) {
        this.agreeForm.expiredValue = dateString
      }
    },
    // 查看协议
    handleLookAgree () { },
    // 表格删除
    handleDelete () { },
    // 新增师资 提交
    addAgreeHandleOk () {
      this.data = this.selectedRows
      this.addAgreeVisible = false
    },
    // 新增师资 取消
    addAgreeHandleCancel () {
      this.addAgreeVisible = false
    },
    // 筛选
    search () {
      this.getAgreeList()
    },
    // 重置
    reset () {
      this.queryParam = {
        directory: [],
        type: '',
        id: '',
        name: '',
        affiliation: undefined
      }
      this.getAgreeList()
    },
    // 有效期时间下拉切换
    expiredGoodsChange () {
      this.agreeForm.expiredValue = undefined
    },
    // 商品有效期切换清除验证
    validityChange (e) {
      this.$refs.agreeForm.resetFields()
      this.agreeForm.validity = e.target.value
    },
    // 获取所属机构
    getAffiliation () {
      affiliation({}).then(res => {
        if (res.code === '1') {
          this.affiliationList = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 获取课程目录
    getDirectory () {
      const data = {
        type: 0,
        directoryLevel: 1
      }
      directory(data).then(res => {
        if (res.code === '1') {
          res.data.forEach(item => {
            item.isLeaf = false
          })
          this.directoryOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 课程目录二级-六级
    loadData (selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const data = {
        type: 1,
        parentId: targetOption.id,
        directoryLevel: 2
      }
      targetOption.loading = true
      directory(data).then(res => {
        if (res.code === '1') {
          if (res.data.length > 0) {
            res.data.forEach(item => {
              item.isLeaf = false
            })
            targetOption.loading = false
            targetOption.children = [...res.data]
          } else {
            targetOption.loading = false
            this.$message.error('暂无更多数据')
          }
        } else {
          targetOption.loading = false
          this.$message.error(res.msg)
        }
        this.directoryOptions = [...this.directoryOptions]
      }).catch(err => {
        this.$message.error(err.msg)
        targetOption.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.agreeForm {
  margin-top: 30px;
}
</style>
<style lang="less">
.w80 {
  .ant-form-item-label {
    width: 80px !important;
  }
}
</style>
